package com.dnui.seven2.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dnui.seven2.common.BaseContext;
import com.dnui.seven2.common.R;
import com.dnui.seven2.entity.Employee;
import com.dnui.seven2.entity.User;
import com.dnui.seven2.service.UserService;
import com.dnui.seven2.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
    @RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R<User> login(HttpServletRequest request,@RequestBody User user){
        //将页面提交的密码加密处理
        String password = user.getUserPwd();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getUserName,user.getUserName());
        User user1 = userService.getOne(queryWrapper);

        //如果没有查到，返回失败结果
        if (user1==null){
            return R.error("登录失败");
        }

        //密码比对
        if (!user1.getUserPwd().equals(password)){
            return R.error("登录失败");
        }


        //登录成功
        request.getSession().setAttribute("user",user1.getUserId());
        return R.success(user1);

    }

    /**
     * 新增员工
     * @param user
     * @return
     */
    @PostMapping("/save")
    public R<String> save(HttpServletRequest request, @RequestBody User user){
        log.info("新增用户信息",user.toString());
        String userPwd = user.getUserPwd();
        //设置初始密码123456，进行md5加密处理
        user.setUserPwd(DigestUtils.md5DigestAsHex(userPwd.getBytes()));

        //获取当前用户登陆id
        Long userId=(Long) request.getSession().getAttribute("user");


        userService.save(user);
        return R.success("新增用户成功");
    }
}
